//
//  CarDetailMainVC.m
//  New_Runway
//
//  Created by mack on 2018/1/25.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "CarDetailMainVC.h"
#import "CarDetailVC.h"
#import "CarConfigureVC.h"
#import "CarBaseInfoModel.h"
#import "CarDetailBottomView.h"
#import "IamgeFactory.h"

#import "NRWCarCarDetailShareView.h"
#import "NRWCarShareTool.h"
#import "NRWShareTemplateView.h"
#import "NRWShareImageAlertView.h"
#import "NRWCarShareTemplateManager.h"

@interface CarDetailMainVC ()<NRWCarCarDetailShareViewDelegate, NRWShareImageAlertViewDelegate>
@property(nonatomic, strong) CarDetailVC *carBaseVC;
@property(nonatomic, strong) CarConfigureVC *carConfigureVC;
@property (nonatomic, strong) NSArray *titles;
@property(strong, nonatomic)NSArray *childVcs;
@property (weak, nonatomic) ZJScrollSegmentView *segmentView;
@property (weak, nonatomic) ZJContentView *contentView;
@property (nonatomic, strong) NSMutableArray *imageUrls;
@property (nonatomic,strong) NSMutableArray *imageUrlNors;
@property (nonatomic, strong) UIView *bottomview;

///图片分享生成的图片  后期优化重构, 不应该放在这里
@property (strong, nonatomic) UIImage *image;

@end

@implementation CarDetailMainVC
{
    CarBaseInfoModel *_infomodel;
}
-(NSMutableArray *)imageUrls{
    if (!_imageUrls) {
        _imageUrls = [[NSMutableArray alloc] init];
    }
    return _imageUrls;
}

-(NSMutableArray *)imageUrlNors{
    if (!_imageUrlNors) {
        _imageUrlNors = [[NSMutableArray alloc] init];
    }
    return _imageUrlNors;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationBarView.titleLabel.text = @"车辆详情";
    self.view.backgroundColor = kColorWhite();
    
    [self setupNavView];
   
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(inputAndOutFactory:) name:@"FactorySuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setCarPrice:) name:@"setPrice" object:nil];

    [self loadCarBaseInfo];

}


- (void)setupNavView {
    
    if (_isShowR == YES) {
        [self.navigationBarView.rightItem setImage:[UIImage imageNamed:@"Point"] forState:UIControlStateNormal];
        [self.navigationBarView.rightItem setTitle:@"" forState: UIControlStateNormal];
    }
    if (self.isShowShare) {
        
        if (isEmptyOrNilString([NRWCarUser sharedUser].shopId)) {
            return;
        }
        
        //修改一下item大小  不然影响布局
        self.navigationBarView.rightItem.setViewWidth(45);
        self.navigationBarView.rightItem.setViewX(self.navigationBarView.rightItem.viewX + 15);
        
        UIButton *rightShareBtn = [[UIButton alloc] init];
        [rightShareBtn setImage:getImageFromName(@"nav_share") forState:UIControlStateNormal];
        [rightShareBtn addTarget:self action:@selector(rightShareBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.navigationBarView addSubview:rightShareBtn];
        [rightShareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.navigationBarView.rightItem.mas_top);
            make.right.equalTo(self.navigationBarView.rightItem.mas_left);
            make.size.equalTo([NSValue valueWithCGSize:self.navigationBarView.rightItem.size]);
        }];
    }
}

-(void)inputAndOutFactory:(NSNotification *)info{
    [self loadCarBaseInfo];
}

-(void)setCarPrice:(NSNotification *)info{
    [self loadCarBaseInfo];

}

-(UIView *)bottomview{
    
    if (!_bottomview) {

    _bottomview = [[UIView alloc] init];
    [self.view addSubview:_bottomview];
    kSelfWeak;
    [_bottomview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.view).mas_offset(0);
        make.height.mas_offset(45 + weakSelf.BotH);
    }];
    _bottomview.layer.shadowOpacity = 0.3;
    _bottomview.layer.shadowColor = [UIColor grayColor].CGColor;
    _bottomview.layer.shadowRadius = 3;
    _bottomview.layer.shadowOffset = CGSizeMake(0,0);
    _bottomview.backgroundColor = UIColorHex(0xf5f5f5);
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    ZJSegmentStyle *style = [[ZJSegmentStyle alloc] init];
    //显示遮盖
    style.showCover = NO;
    style.showLine = NO;
    style.titleFont = [UIFont boldSystemFontOfSize:14];
    style.segmentViewBounces = NO;
    // 颜色渐变
    style.autoAdjustTitlesWidth =  YES;
    style.gradualChangeTitleColor = NO;
    style.normalTitleColor = MAIN_FONT_COLOR();
    style.selectedTitleColor = MAIN_NAV_COLOR();
    self.titles = @[@"基本信息", @"配置信息"];
    style.titleMargin = 20;
    style.segmentHeight = 40;
    ZJScrollSegmentView *segment = [[ZJScrollSegmentView alloc] initWithFrame:CGRectMake(0, 0,Screen_width, 45) segmentStyle:style delegate:nil titles:self.titles titleDidClick:^(ZJTitleView *titleView, NSInteger index) {
        [weakSelf.contentView setContentOffSet:CGPointMake(weakSelf.contentView.bounds.size.width * index, 0.0) animated:YES];
        
    }];
    
    [_bottomview addSubview:segment];
    segment.backgroundColor = UIColorHex(0xf5f5f5);
    self.segmentView = segment;
    }

    return _bottomview;
}

-(void)initLineView{
    kSelfWeak;
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = UIColorHex(0xcccccc);
    [self.view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.view).mas_offset(-self.BotH - 5);
        make.width.mas_equalTo(1);
        make.height.mas_equalTo(35);

    }];
    [self.view bringSubviewToFront:line];
    
}

- (void)setupContentView {
    
    ZJContentView *content = [[ZJContentView alloc] initWithFrame:CGRectMake(0, self.navH, self.view.bounds.size.width, self.view.bounds.size.height - self.navH  - self.BotH - 45) segmentView:self.segmentView parentViewController:self delegate:self];
    content.backgroundColor = [UIColor purpleColor];
    self.contentView = content;
    [self.view addSubview:self.contentView];
    [self.view bringSubviewToFront:self.bottomview];
}

- (NSInteger)numberOfChildViewControllers {
    return self.titles.count;
}

- (UIViewController<ZJScrollPageViewChildVcDelegate> *)childViewController:(UIViewController<ZJScrollPageViewChildVcDelegate> *)reuseViewController forIndex:(NSInteger)index {
    
    
    if (!reuseViewController) {
        reuseViewController = self.childVcs[index];
    }
    
    return reuseViewController;
}
- (NSArray *)setupChildVc {
    
    
    NSArray *childVcs = [NSArray arrayWithObjects:self.carBaseVC,self.carConfigureVC,nil];
    return childVcs;
}
-(CarDetailVC *)carBaseVC{
    
    if (!_carBaseVC) {
        _carBaseVC = [[CarDetailVC alloc] init];
        
    }
    _carBaseVC.carID = _carID;
    _carBaseVC.imageUrls = self.imageUrls;
    _carBaseVC.norImageUrls = self.imageUrlNors;
    _carBaseVC.infomodel =  _infomodel;
    return _carBaseVC;
}

-(CarConfigureVC *)carConfigureVC{
    if (!_carConfigureVC) {
        _carConfigureVC = [[CarConfigureVC alloc] init];
       
    }
    _carConfigureVC.carID = self.carID;
    _carConfigureVC.modelID = self.modelID;
    _carConfigureVC.infomodel =  _infomodel;
    return _carConfigureVC;
}
-(void)loadCarBaseInfo{
    NSInteger imageViewId = 2;
//    if (self.showImageId == 1) {
//        imageViewId = 3;
//    }
    [SVProgressHUD show];
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",Api,carDetailApi] refreshRequest:YES cache:NO params:@{@"carId":self.carID,@"imageViewId":@(imageViewId)} progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        _infomodel = [CarBaseInfoModel mj_objectWithKeyValues:response];
        
        if (_infomodel.code == 1) {
            [self.imageUrls removeAllObjects];
        for (NSDictionary *dic in _infomodel.result.carImages) {
            CarCarimages *imagemodel =  [CarCarimages mj_objectWithKeyValues:dic];
            [self.imageUrls addObject:[NSString stringWithFormat:@"%@%@",ImageApi,imagemodel.imageUrl]];
            [self.imageUrlNors addObject:[NSString stringWithFormat:@"%@%@",ImageApi,imagemodel.imageUrl]];
            
            [self saveCarImageUrl:imagemodel.imageKey imageUrl:imagemodel.imageUrl];
          
        }
        [self.view addSubview:self.bottomview];
        self.childVcs = [self setupChildVc];
        [self setupContentView];
        [self initLineView];

        
        }
        [SVProgressHUD dismiss];

    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];

        [SVProgressHUD dismiss];
        
    }];
    
}
-(void)saveCarImageUrl:(NSString *)imageKey imageUrl:(NSString *)imageUrl{
    IamgeFactory *iamgeUser = [IamgeFactory sharedMemory];
    [iamgeUser setValue:imageUrl forKey:imageKey];
    [iamgeUser save];
}

-(void)rightItemClick{
    if (_isShowR == YES) {
        CarDetailBottomView *bottomview;
        [bottomview removeFromSuperview];
        bottomview = [[CarDetailBottomView alloc] init];
        bottomview.infomodel = _infomodel;
        bottomview.selIndex = self.selIndex;
        bottomview.nav = self.navigationController;
        bottomview.isReject = self.isReject;
        [self.view addSubview:bottomview];
    }
}

-(void)leftItemClick{
    [self.navigationController popViewControllerAnimated:YES];
    [IamgeFactory reset];
}

- (void)rightShareBtnDidClick:(UIButton *)sender {
    
    NRWCarCarDetailShareView *shareView = [[NRWCarCarDetailShareView alloc] init];
    shareView.delegate = self;
    [shareView show];
}

#pragma mark - NRWCarCarDetailShareViewDelegate
- (void)carDetailShareView:(NRWCarCarDetailShareView *)view shareBtn:(UIButton *)sender didClickAtIndex:(NSInteger)index title:(NSString *)title {
    
    [self.view endEditing:YES];
    
    [view dismiss];
    
    ShareType type = -1;
    
    switch (index) {
        case 0:
            type = ShareTypeWeiXin;
            break;
        case 1:
            type = ShareTypeWXCircle;
            break;
        case 2:
            type = ShareTypeQQ;
            break;
        case 3:
            type = ShareTypeQQCircle;
            break;
        default:
            break;
    }
    
    if (index == 4) {//保存图片
        [SVProgressHUD show];
        NRWShareTemplateView *view = [[NRWShareTemplateView alloc] init];
        view.model = _infomodel;
        dispatch_sync(dispatch_get_global_queue(0, 0), ^{
            view.carImage = [NRWCarShareTemplateManager downloadSingleImageWithUrl:[NSString stringWithFormat:@"%@%@", ImageApi, _infomodel.result.carImageUrl]];
            UIImage *image = [NRWCarShareTemplateManager getViewScreenshots:view];
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:),nil);
        });
    } else {
        if (view.showSavePhotoBtn) {//分享车辆详情
            [NRWCarShareTool shareCarDetailWithCarDetailModel:_infomodel shareType:type];
        } else {//分享单车模板图片
            [NRWCarShareTool shareImage:self.image WithShareType:type];
        }
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo {
 
    [SVProgressHUD dismiss];
    self.image = image;
    NRWShareImageAlertView *view = [[NRWShareImageAlertView alloc] init];
    view.image = image;
    view.delegate = self;
    [view show];
}

#pragma mark - NRWShareImageAlertViewDelegate
- (void)shareImageAlertView:(NRWShareImageAlertView *)view shareBtn:(UIButton *)sender didClickWithImage:(UIImage *)image {
    
    [view dismiss];
    NRWCarCarDetailShareView *shareView = [[NRWCarCarDetailShareView alloc] init];
    shareView.delegate = self;
    shareView.showSavePhotoBtn = NO;
    [shareView show];
}

@end
